import axios from 'axios'
import { Loading, MessageBox } from 'element-ui'
import apis from '@/config/api'
import {pageSize} from '@/config'

export default {
  // ajax方法
  ajax ({dispatch, getters}, {url, method = 'post', params = {}, data = {}}) {
    // loading的句柄
    let loadingInstance = ''
    let ajax = null
    // 请求前打开loading图
    axios.interceptors.request.use(config => {
      loadingInstance = Loading.service({
        customClass: 'data-loading',
        text: '正在加载中....'
      })
      return config
    }, err => Promise.reject(err))
    // 判断请求方式
    if (method === 'get' || method === 'delete') {
      ajax = axios.get(url, {
        headers: {
          Authorization: localStorage.getItem('token')
        },
        params: params
      })
    } else if (method === 'post' || method === 'patch') {
      ajax = axios.post(url, data, {
        headers: {
          Authorization: localStorage.getItem('token')
        }
      })
    }
    // 返回promise
    return ajax.then(res => {
      // 请求成功后关闭loading
      loadingInstance.close()
      // 如果响应状态码不正常，则弹窗
      if (res.data.status === 'fail') {
        MessageBox(res.data.data)
        return Promise.reject(res.data.msg)
      }
      return res.data
    }, err => {
      loadingInstance.close()
      MessageBox(err.message)
      console.log('请求程序出错：', err)
    })
  },

  // 注册教师
  registerTeacher ({dispatch}, {code, name, pwd}) {
    return dispatch('ajax', {
      url: apis.registerTeacher,
      data: {
        code: code,
        name: name,
        pwd: pwd
      }
    })
  },
  // 登录教师
  loginTeacher ({dispatch}, {code, pwd}) {
    return dispatch('ajax', {
      url: apis.loginTeacher,
      data: {
        code: code,
        pwd: pwd
      }
    })
  },

  // 分页获取课程
  getCourseByPage ({dispatch}, {pageNum}) {
    return dispatch('ajax', {
      url: apis.getCourseByPage,
      method: 'get',
      params: { pageNum, pageSize }
    })
  },

  // 新增一个课程
  addCourse ({dispatch}, {code, name}) {
    let tid = JSON.parse(localStorage.getItem('userInfo'))._id
    return dispatch('ajax', {
      url: apis.addCourse,
      data: { code, name, tid }
    })
  },

  // 分页获取签到
  getSignByPage ({dispatch}, {pageNum, cid}) {
    return dispatch('ajax', {
      url: apis.getSignByPage,
      method: 'get',
      params: {pageNum, cid, pageSize}
    })
  },

  // 新增一个签到
  addSign ({dispatch}, data) {
    return dispatch('ajax', { url: apis.addSign, data })
  }

}
